import axios from "axios"
import qs from "qs"
import Vue from "vue"
import store from 'store'
// 本地环境
// export const BASEURL = 'http://192.168.1.15:83/' // 张瑞赟
// export const BASEURL = 'http://192.168.1.37:82/' // 张瑞赟
export const BASEURL = 'https://erp.zhuiyun.net/erpc/' // 正式环境 API

export const uploadImgUrl = 'https://zhuiyunerp.eos-shanghai-1.cmecloud.cn/upload/' //正式环境



//自己定义个适配器，用来适配uniapp的语法
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		// console.log(config)
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				// console.log("执行完成：", response)
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}

const service = axios.create({
	// withCredentials: true,
	// crossDomain: true,
	baseURL: BASEURL, //接口共供地址
	timeout: 6000,
})



// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		const accessToken = uni.getStorageSync('visitorAccessToken') ? JSON.parse(uni.getStorageSync(
			'visitorAccessToken')) : ''
		// const accessToken = store?.state?.token || ''
		if (accessToken) {
			// 给请求头添加user-token
			config.headers["accessToken"] = accessToken;
		}
		config.method === 'post' ?
			config.data = qs.stringify(config.data, {
				indices: false
			}) :
			config.params = qs.stringify(config.params, {
				indices: false
			});
		return config;
	},
	error => {
		console.log(error); // for debug
		return Promise.reject(error);
	}
);

//配置成功后的拦截器
service.interceptors.response.use(res => {
	if (res.status == 200) {
		if (res.data.code == 2000) {
			return res.data
		} else if (res.data.code == 4006) {
			setTimeout(() => {
				// uni.clearStorage();
				uni.removeStorageSync('visitorLoginInfo')
				uni.removeStorageSync('visitorAccessToken');
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}, 1000)
			return res.data;
		} else {
			return res.data;
		}
	} else {
		return Promise.reject(res.data.msg);
	}
}, error => {
	return Promise.reject(error)
})


export default service